package com.pig4cloud.pig.ads.gdt.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.common.collect.Lists;
import com.pig4cloud.pig.ads.gdt.service.GdtAccesstokenService;
import com.pig4cloud.pig.ads.gdt.service.GdtCustomAudiencesService;
import com.pig4cloud.pig.ads.gdt.service.GdtSceneSpecService;
import com.pig4cloud.pig.ads.service.TtAccesstokenService;
import com.pig4cloud.pig.ads.utils.OEHttpUtils;
import com.pig4cloud.pig.api.gdt.dto.*;
import com.pig4cloud.pig.api.util.MapUtils;
import com.pig4cloud.pig.common.core.util.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.groovy.util.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class GdtSceneSpecServiceImpl implements GdtSceneSpecService {

	@Autowired
    GdtAccesstokenService gdtAccesstokenService;

	@Autowired
    TtAccesstokenService ttAccesstokenService;

	@Autowired
    GdtCustomAudiencesService gdtCustomAudiencesService;

	@Autowired
	StringRedisTemplate stringRedisTemplate;
	@Value("${gdt_scene_spec_tags_url:https://api.e.qq.com/v1.3/scene_spec_tags/get}")
	String sceneSpecTagsUrl;
	@Value("${gdt_union_position_packages_url:https://api.e.qq.com/v1.3/union_position_packages/get}")
	String unionPositionPackagesUrl;
	@Value("${gdt_union_position_packages_url:https://api.e.qq.com/v1.3/union_position_packages/add}")
	String unionPositionPackagesCreateUrl;
	@Override
	public R getGdtSenPositionTags(String accountId, String type) {
		String url = String.format("%s%s&%s",sceneSpecTagsUrl, getUrlTail(accountId),MapUtils.queryString(Maps.of("account_id",accountId,"type",type)));
		String resultStr = OEHttpUtils.doGdtGet(url, null);
		if(StringUtils.isNotBlank(resultStr)){
			GdtResult<GdtResultData<GdtSceneSpecTags>> result=JSON.parseObject(resultStr,new TypeReference<GdtResult<GdtResultData<GdtSceneSpecTags>>>(){});
			if(Objects.isNull(result)){
				return R.failed("获取媒体类型数据失败");
			}
			if(result.getCode() != 0 ){
				return R.failed(result.getMessage());
			}
			return R.ok(result.getData());
		}
		return R.failed("获取媒体类型数据失败");
	}

	@Override
	public R getGdtUnionPositionPackages(String accountId, String type,int page,int pageSize) {
		FilteringDto dto=new FilteringDto();
		dto.setField("union_package_type");
		dto.setOperator("EQUALS");
		dto.setValues(new String[]{type});
		Map<String,String> reqData=Maps.of("account_id",accountId,"filtering",JSON.toJSONString(Lists.newArrayList(dto)),"page",String.valueOf(page),"page_size",String.valueOf(pageSize));
		String url = String.format("%s%s&%s",unionPositionPackagesUrl, getUrlTail(accountId),MapUtils.queryString(reqData));
		String resultStr = OEHttpUtils.doGdtGet(url, null);
		if(StringUtils.isNotBlank(resultStr)){
			GdtResult<GdtResultData<GdtUnionPackageDto>> result=JSON.parseObject(resultStr,new TypeReference<GdtResult<GdtResultData<GdtUnionPackageDto>>>(){});
			if(Objects.isNull(result)){
				return R.failed("获取流量包数据失败");
			}
			if(result.getCode() != 0 ){
				return R.failed(result.getMessage());
			}
			return R.ok(result.getData());
		}
		return R.failed("获取流量包数据失败");
	}
	@Override
	public R createGdtUnionPositionPackages(GdtUnionPackageDto gdtUnionPackageDto) {
		String url = String.format("%s%s",unionPositionPackagesCreateUrl, getUrlTail(String.valueOf(gdtUnionPackageDto.getAccount_id())));
		String resultStr = OEHttpUtils.doPost(url, JSON.parseObject(JSON.toJSONString(gdtUnionPackageDto),Map.class));
		if(StringUtils.isNotBlank(resultStr)){
			GdtResult<JSONObject> result=JSON.parseObject(resultStr,GdtResult.class);
			if(Objects.isNull(result)){
				log.error("未正常返回业务数据");
				return R.failed("获取流量包数据失败");
			}
			if(result.getCode() != 0 ){
				log.error(result.getMessage());
				return R.failed(result.getMessage());
			}
			if(Objects.isNull(result.getData())){
				log.error("未正常返回业务数据");
				return R.failed("获取流量包数据失败");
			}
			Integer union_package_id;
			if(Objects.isNull(union_package_id=result.getData().getInteger("union_package_id"))){
				log.error("未返回流量包ID");
				return R.failed("获取流量包数据失败");
			}else {
				return R.ok(union_package_id);
			}
		}
		log.error("未正常返回业务数据");
		return R.failed("获取流量包数据失败");
	}
	private String getUrlTail(String accountId){
		Map<String, String> map = gdtAccesstokenService.fetchAccesstoken(accountId);
		String gdtToken = map.get("access_token");
		int nonce = RandomUtils.nextInt();
		long tsp = Math.round(System.currentTimeMillis() / 1000);
		String tail = String.format("?access_token=%s&timestamp=%d&nonce=%d", gdtToken, tsp, nonce);
		return tail;
	}
}
